<?php

namespace IMOcean\Utils\DB;

/**
 * Class DBUtils
 *
 * @Pattern Simple Factory Pattern
 * @package IMOcean\Utils\DB
 */
class DBUtils
{
    /**
     * Database link parameters: MySQL
     */
    const MySQL = [
        'dsn' => 'mysql:host=127.0.0.1;port=3306;dbname=im',
        'user' => 'root',
        'password' => 'ziyuyu'
    ];

    /**
     * Database link parameters: Redis
     */
    const Redis = [
        'host' => '127.0.0.1',
        'port' => 6379,
        'password' => 'ziyuyu'
    ];

    /**
     * Get database connection
     * @access public
     * @static
     * @param string $type connection type
     * @return \PDO|\Redis|null
     * @throws \RedisException
     */
    public static function getConnection(string $type): \PDO|\Redis|null
    {
        $connection = null;

        switch ($type) {
            case 'MySQL':
                try {
                    $connection = new \PDO(self::MySQL['dsn'], self::MySQL['user'], self::MySQL['password']);
                } catch (\PDOException $e) {
                    die ("Error!: " . $e->getMessage() . PHP_EOL);
                }

                break;
            case 'Redis':
                $connection = new \Redis();

                $connection->connect(self::Redis['host'], self::Redis['port']);
                $connection->auth(self::Redis['password']);

                if (!$connection->ping()) self::close($type, $connection);

                break;
            default: break;
        }

        return $connection;
    }

    /**
     * Close resource
     * @access public
     * @static
     * @param string $type resource type
     * @param \PDO|\Redis $connection
     */
    public static function close(string $type, \PDO|\Redis $connection)
    {
        switch ($type) {
            case 'MySQL':
                $connection = null;
                break;
            case 'Redis':
                $connection->close();
                break;
            default:
                break;
        }
    }
}